package com.jxk.zuul.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jxk.common.util.JwtUtils;
import com.jxk.common.util.Result;
import com.jxk.zuul.config.BasicConf;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.micrometer.core.instrument.util.JsonUtils;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 认证过滤器
 **/
public class AuthFilter extends ZuulFilter {
    @Autowired
    private BasicConf basicConf;

    public AuthFilter() {
        super();
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        ObjectMapper mapper = new ObjectMapper();
        HttpServletRequest request = ctx.getRequest();
        String apis = basicConf.getApiWhiteStr();
        // 白名单，放过
        List<String> whileApis = Arrays.asList(apis.split(","));
        String uri = request.getRequestURI();
        if (whileApis.contains(uri)) {
            return null;
        }
        // path uri 处 理
        for (String wapi : whileApis) {
            if (wapi.contains("{") && wapi.contains(")")) {
                if (wapi.split("/").length == uri.split("/").length) {
                    String reg = wapi.replaceAll("\\{.*}", ".*{1,}");
                    Pattern r = Pattern.compile(reg);
                    Matcher m = r.matcher(uri);
                    if (m.find()) {
                        return null;
                    }
                }
            }

        }
       String token= request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            ctx.setSendZuulResponse(false);
            ctx.set("isSuccess", false);
            try {
                ctx.setResponseBody(mapper.writeValueAsString(Result.error().message("非法请求【缺少 Authorization 信息")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ctx.getResponse().setContentType("application/json; charset=utf-8");
            return null;
        }

        if (! JwtUtils.checkToken(token)) {
            ctx.setSendZuulResponse(false);
            ctx.set("isSuccess", false);
            try {
                ctx.setResponseBody(mapper.writeValueAsString(Result.error().message("token非法")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            ctx.getResponse().setContentType("application/json; charset=utf-8");
            return null;
        }
        ctx.addZuulRequestHeader("uid",JwtUtils.getMessageByToken(token) );
        return null;
    }
}